#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Lee
# @File    : dhy_resource_data_update.py
# @Time    : 2023/12/5 15:20

import os
import re
import json
import time

import pymysql


class MysqlHandler:
    def __init__(self, host='192.168.1.57', port=3306, user='root', pwd='123456'):
        self.mysql = pymysql.Connect(host=host, user=user, password=pwd, port=port, charset="utf8", autocommit=True)
        self.cursor = self.mysql.cursor(pymysql.cursors.DictCursor)

    def execute_sql(self, sql):
        """
        插入、更新数据
        """
        try:
            self.cursor.execute(sql)  # 通过游标执行SQL查询
            self.mysql.commit()
        except Exception as e:
            self.mysql.rollback()
            raise ("数据库查询出错：", e.message)

    def close_mysql(self):
        """
        作用：关闭查询页面，关闭数据库连接。
        """
        self.cursor.close()
        self.mysql.close()


def is_ip_address(line_str):
    pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$'
    result = re.match(pattern, line_str.split(":")[0])
    return True if result else False


def analysis_resource_collection_data():
    _mysql_handler = MysqlHandler()
    for file_name in os.listdir("../data"):
        _data_list = list()
        if file_name[-4:] == ".txt":
            with open(os.path.join("../data", file_name), 'r')as f_obj:
                for line_data in f_obj.readlines():
                    if len(line_data.strip()) == 0:
                        continue
                    _line_json = json.loads(line_data.strip())
                    if type(_line_json) != dict:
                        continue
                    _data_list.append([_line_json["timestamp"],
                                       [["planning", *_line_json["planning"]],
                                        ["control", *_line_json["control"]],
                                        ["localization", *_line_json["localization_component"]],
                                        ["client", *_line_json["Client"]]]])
            _start_time = _data_list[0][0]
            sql_str = """INSERT INTO ufo_auto.dhy_resource_data (start_time, host_ip,memory_data) value
            ('{}', '{}', '{}')""".format(_start_time, "", json.dumps(_data_list))
            _mysql_handler.execute_sql(sql_str)


if __name__ == '__main__':
    analysis_resource_collection_data()
    # with open("2023_11_29_16.txt", "r") as file_obj:
    #     for line_data in file_obj:
    #         if not is_ip_address(line_data):
    #             format_line_data = eval(line_data)
    #             _new_line_data = [format_line_data[0]]
    #             _line = list()
    #             for item in format_line_data[1]:
    #                 for key, value in item.items():
    #                     _line.append([key, *value])
    #             _new_line_data.append(_line)
    #             with open("_test_data.txt", 'a') as f_obj:
    #                 if len(_new_line_data) > 1:
    #                     f_obj.write(json.dumps(_new_line_data) + "\n")
